package com.jy.wms.controller;

import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.SetStatus;
import com.jy.wms.common.base.*;
import com.jy.wms.pojo.*;
import com.jy.wms.service.WmsOwnerSupplierService;
import com.jy.wms.service.WmsShelvesService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.jy.wms.service.WmsFailedLibraryService;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.github.pagehelper.Page;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jy.wms.common.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @ClassName: WmsFailedLibraryController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author LH
 * @Date Tue Jan 23 09:32:55 GMT+08:00 2018
 */
@RestController
@RequestMapping("/wmsfailedlibrary")
@Api(value = "/wmsfailedlibrary", description = "不合格品处理操作（出库）")
public class  WmsFailedLibraryController extends BaseController<WmsFailedLibraryService,WmsFailedLibrary> {

    @Autowired
    private WmsShelvesService wmsShelvesService;
    /**
     * 当前仓库，当前货主下的质检状态为   “4”（质检完成） 的预期到货通知单（ASN）
     * @param entity  预期到货通知单 实体类
     * @param session
     * @return
     */
    @PostMapping(value = "/list")
    @ApiOperation(value = "查询信息",response = JSONObject.class, notes = "查询信息")
    public @ResponseBody JSONObject getWmsFailedLibrary(@RequestBody WmsEstimatedArrivalOrder entity,HttpSession session) {
        JSONObject json = getJSONObject();
        try {
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            List<SysHz> hz = (List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
            Page<WmsEstimatedArrivalOrder> list = new Page<WmsEstimatedArrivalOrder>();
            String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
            String ckmc = userinfo.getUser().getOrgName();//仓库名称
            if(hz.size()>0){
                list= baseService.baseSelectPage(entity,hz.get(0).getHzid(),ckid,ckmc,hz.get(0).getShow_hzid());            }
            json = SetStatus.setSearchType(JSONArray.fromObject(list).toString(),(int) list.getTotal());
        } catch (ServiceException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
       return json;
    }

    @PostMapping(value = "/getReceiveList")
    @ApiOperation(value = "查询收货信息（不合格入库页面）",response = JSONObject.class, notes = "查询输入</br>{\"asnId\":\"asnId\"，\"page\":\"页\"，\"rows\":\"行\"}")
    public @ResponseBody JSONObject getReceiveList(@RequestBody Map map, HttpSession session) {
        JSONObject json = getJSONObject();
        try {
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            List<SysHz> hz = (List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
            Page<WmsShelves> list = new Page<WmsShelves>();
            String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
            String ckmc = userinfo.getUser().getOrgName();//仓库名称
            if(hz.size()>0){
                list= baseService.getReceiveList((String)map.get("asnId"),(Integer)map.get("page"),(Integer)map.get("rows"));
            }
            json = SetStatus.setSearchType(JSONArray.fromObject(list).toString(),(int) list.getTotal());
        } catch (ServiceException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 库位模糊查询
     * @param map
     * @param session
     * @return
     */
    @PostMapping(value="/searchKw")
    @ApiOperation(value = "不合格品处理 库位模糊查询",response = JSONObject.class, notes = "查询输入{\"show_kwid\":\"库位模糊查询\"}")
    public @ResponseBody JSONArray searchKw(@RequestBody Map<String,String> map,HttpSession session) {
        List<WmsLibraryPosition> list = new ArrayList<WmsLibraryPosition>();
        try {
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            String ckid=String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库编号
            String hzid=null;//取当前货主编号
            List<SysHz> hz= (List<SysHz>) session.getAttribute(BaseSessionInfo.SessionConsignor);
            if(hz.size()>0){
                hzid=hz.get(0).getHzid();
            }
            list = baseService.searchKw(map.get("show_kwid"),ckid,hzid);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONArray.fromObject(list);
    }


    /**
     * 上架管理 新增上架信息
     * @param list
     * @param session
     * @return
     */
    @PostMapping(value = "/add")
    @ApiOperation(value = "不合格品出库 新增出库信息",response = JSONObject.class, notes = "POST新增出库信息")
    public @ResponseBody JSONObject addWmsLibraryPosition(@RequestBody List<WmsShelves> list,HttpSession session) {
        JSONObject json = getJSONObject();
        try {
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            String ckid=String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库编号
            String hzid=null;//取当前货主编号
            List<SysHz> hz= (List<SysHz>) session.getAttribute(BaseSessionInfo.SessionConsignor);
            if(hz.size()>0){
                hzid=hz.get(0).getHzid();
            }
            baseService.add(list,userinfo.getUser().getName(),ckid);
           // baseService.add(list,ckid,hzid,session);
            json = SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.success.toString(),"确认出库信息成功","", JSONArray.fromObject(list).toString());
        }catch (SucessException e){
            e.printStackTrace();
            json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.warning.toString(),"确认出库信息成功",e.getMessage(),"");
        } catch (ServiceException e){
            e.printStackTrace();
            json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.warning.toString(),"确认出库信息失败",e.getMessage(),"");
        }catch (Exception e) {
            e.printStackTrace();
            json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.error.toString(),"确认出库信息失败",e.getMessage(),"");
        }
        return json;
    }

    /**
     * 质检单明细查询
     * @param map
     * @param session
     * @return
     */
    @PostMapping(value="/getQualityDetail")
    @ApiOperation(value = "不合格品处理 质检单明细查询",response = JSONObject.class, notes = "查询输入{\"asnId\":\"asnId\",\"page\":\"页\"，\"rows\":\"行\"}")
    public @ResponseBody JSONObject getQualityDetail(@RequestBody Map map,HttpSession session) {
      JSONObject json=getJSONObject();
        Page<WmsQualityInspectionListDetailed> list = new Page<WmsQualityInspectionListDetailed>();
        try {

            list = baseService.getQualityDetail((String)map.get("asnId"),(Integer) map.get("page"),(Integer)map.get("rows"));
            json = SetStatus.setSearchType(JSONArray.fromObject(list).toString(),(int) list.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }



    /**
     * 质检单附件查询
     * @param map
     * @param session
     * @return
     */
    @PostMapping(value="/getQcEnclosure")
    @ApiOperation(value = "不合格品处理 质检单附件查询",response = JSONObject.class, notes = "查询输入{\"asnId\":\"asnId\",\"page\":\"页\"，\"rows\":\"行\"}")
    public @ResponseBody JSONObject getQcEnclosure(@RequestBody Map map,HttpSession session) {
        JSONObject json=getJSONObject();
        Page<WmsQcEnclosure> list = new Page<WmsQcEnclosure>();
        try {
            list = baseService.getQcEnclosure((String)map.get("asnId"),(Integer) map.get("page"),(Integer)map.get("rows"));
            json = SetStatus.setSearchType(JSONArray.fromObject(list).toString(),(int) list.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }



    @ApiOperation(value = "导出不合格品处理入库信息", response = JSONObject.class, notes = "导出不合格品处理入库信息")
    @PostMapping(value = "getOutPutList")
    public JSONObject getOutPutList(HttpServletResponse response,@RequestBody Map map,HttpSession session) throws IOException {
        String filename = "不合格品处理入库导出";
       // UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
        //String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
        String ckid ="2";
       // String ckmc = userinfo.getUser().getOrgName();//仓库名称
        map.put("ckid", ckid);
        List<String> ids = (List) map.get("ids");
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("不合格品处理入库信息", "UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        ExportParams ep = new ExportParams();
        ep.setStyle(ManySheetOneSyler.class);
        List<WmsShelves> list = null;
        map.put("ssck", "d");
        list= baseService.getReceiveListOutPut(ids,map);
        Workbook workbook = ExcelExportUtil.exportExcel(ep, WmsShelves.class, list);
        workbook.write(response.getOutputStream());
        return null;
    }














}
